package com.distributeredis.redis_springboot.springbooteasyexcel.write.goodListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.distributeredis.redis_springboot.springbooteasyexcel.vo.Goods;
import com.distributeredis.redis_springboot.springbooteasyexcel.vo.GoodsExcelDTO;
import com.distributeredis.redis_springboot.springbooteasyexcel.write.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Excel模板的读取类
 * 有个很重要的点 DemoDataListener 不能被spring管理
 * 要每次读取excel都要new, 然后里面用到spring可以构造方法传进去
 */
@Slf4j
public class GoodsListener implements ReadListener<GoodsExcelDTO> {
    @Autowired
    private GoodsService goodsService;

    private List<GoodsExcelDTO> goodsExcelDTOList = ListUtils.newArrayList();
    private final List<Goods> goodsList = ListUtils.newArrayList();
    private int count = 0;

    public GoodsListener() {
    }

    public GoodsListener(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @Override
    public void invoke(GoodsExcelDTO goodsExcelDTO, AnalysisContext analysisContext) {
        log.info("解析到第 {} 条数据:{}", (++count), JSON.toJSONString(goodsExcelDTO));
        goodsExcelDTOList.add(goodsExcelDTO);
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        Map<Integer, String> stringMap = ConverterUtils.convertToStringMap(headMap, context);
        Set<Integer> keySet = stringMap.keySet();
        System.out.println("该Excel表头信息是：");
        for (int i = 0; i < keySet.size(); i++) {
            System.out.println("第 " + (i + 1) + " 列 = " + stringMap.get(i));
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("该Excel的所有数据解析完成！！！");
        goodsExcelDTOList.forEach(item -> {
            try {
                Goods goods = new Goods();
                goods.setId(item.getId());
                goods.setName(item.getName());
                goods.setInfo(item.getInfo());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = sdf.parse(item.getBuyTime());
                goods.setBuyTime(date);
                goodsList.add(goods);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        });
        goodsExcelDTOList = ListUtils.newArrayList();
        goodsService.batchInsert(goodsList);
    }
}

